package com.xywy.tangandroid.activity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.xywy.tangandroid.R;
import com.xywy.tangandroid.adapter.BloodDataListAdapter;
import com.xywy.tangandroid.base.BaseActivity;
import com.xywy.tangandroid.bean.BloodComputor;
import com.xywy.tangandroid.bean.BloodData;
import com.xywy.tangandroid.bean.User;
import com.xywy.tangandroid.greendao.BaseDao;
import com.xywy.tangandroid.greendao.BloodDataDao;
import com.xywy.tangandroid.greendao.BloodDataDao.Properties;
import com.xywy.tangandroid.receiver.BroadcastAction;
import com.xywy.tangandroid.util.Constant;
import com.xywy.tangandroid.util.JsonUtil;
import com.xywy.tangandroid.util.MD5;
import com.xywy.tangandroid.util.UIUtil;
import com.xywy.tangandroid.vollery.GetRequest;
import com.xywy.tangandroid.vollery.OnVolleyResponseListener;
import com.xywy.tangandroid.vollery.PostRequest;
import com.xywy.tangandroid.vollery.VolleyManager;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * *****************************************
 * 
 * @Title: BloodDataList.java
 * @Package com.xywy.tangandroid.activity
 * @Description: TODO(血糖数据列表)
 * @author smz
 * @date 2014-12-4 下午5:20:33
 * @version V1.0
 ******************************************* 
 */
public class BloodDataListAct extends BaseActivity {
	private List<BloodData> list;
	private BloodDataListAdapter adapter;
	private ListView listView;
	private String sign;
	private RelativeLayout left_img;
	private TextView middle_title;
	private BroadcasrReciver receiver;

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.act_blooddata_list);
		try {
			sign = MD5.md5s(Constant.pwd + User.getIUserInstance(context).getUserid() + "xywy_xuetang");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		left_img = (RelativeLayout) findViewById(R.id.left_img);
		middle_title = (TextView) findViewById(R.id.middle_title);
		middle_title.setText(R.string._blood_info);
		listView = (ListView) findViewById(R.id.listview);
		list = new ArrayList<BloodData>();
		adapter = new BloodDataListAdapter(context, list);
		listView.setAdapter(adapter);

		IntentFilter filter = new IntentFilter(BroadcastAction.ACCTION_DELETE_BLOOD_DATA);
		receiver = new BroadcasrReciver();
		registerReceiver(receiver, filter);
	}

	public class BroadcasrReciver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			System.out.println("获取的广播是什么呢.." + intent.getAction());
			// Message msg = Message.obtain();
			if ("action_detele_blood_data".equals(intent.getAction())) {
				// msg.what = REQUESTdOCTORLIST;
				// handler.sendMessage(msg);
				BloodData data = (BloodData) intent.getSerializableExtra("data");
				 int position = intent.getIntExtra("position", -1);
				 Log.e("onreceive--adapter", position+"");
				 deleteBloodData(data,position);

			}
		}

	}

	/**
	 * 删除血压的数据
	 */
	public void deleteBloodData(BloodData dataItem,final int position) {
		String url = "http://api.yun.xywy.com/index.php/api/setdata/del_xuetang/";
		PostRequest<String> postRequest = new PostRequest<String>(url, String.class, new OnVolleyResponseListener<String>() {

			@Override
			public void onError(VolleyError volleyError) {
				System.out.println(volleyError);
				UIUtil.DissDialog(context, waittingDialog);
				UIUtil.showToast(context, getResources().getString(R.string.network_slow));
			}

			@Override
			public void onSuccess(String response) {
				UIUtil.DissDialog(context, waittingDialog);
				System.out.println("删除数据返回的信息..." + response);
				JSONObject object;
				try {
					object = new JSONObject(response);
					int state = object.optInt("state");
					String error = object.optString("error");
					if (state == 200) {
						bloodDao.delete(list.get(position));
						list.remove(position);
						adapter.notifyDataSetChanged();
					} else {
						UIUtil.showToast(context, error);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

		HashMap<String, String> params = new HashMap<String, String>();
		params.put("sn",sign);
		params.put("app_username", "xywy_xuetang");
		params.put("xywy_userid", User.getIUserInstance(context).getUserid());
		params.put("app_data", dataItem.getApp_data());
		params.put("shou_data", dataItem.getShou_data());
		params.put("datatime", dataItem.getRecordtime());
		postRequest.setParams(params);
		postRequest.setIsParseJson(false);
		executeRequest(postRequest);
	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
	}

	@Override
	protected void initData() {
		BaseDao basedao = BaseDao.getInstance(this);
		bloodDao = basedao.getBloodDataDao();
		getBloodList();
	}

	BloodDataDao bloodDao;
	/**
	 * 获取上传的血糖数据列表
	 */
	private void getBloodList() {
		QueryBuilder<BloodData> qb = bloodDao.queryBuilder();
		qb.orderDesc(Properties.Recordtime);
		if(qb.list() != null){
			list.addAll(qb.list());
			Collections.sort(list, new BloodComputor());
			adapter.notifyDataSetChanged();
		}
	}
	

	/**
	 * 解析
	 * 
	 * @param optJSONObject
	 */
	protected void ParseBloodDataList(String data) {
		List<BloodData> tempData = (List<BloodData>) JsonUtil.parseJsonToList(data, new TypeToken<List<BloodData>>() {
		}.getType());
		list.addAll(tempData);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.left_img:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		VolleyManager.cancelRequest(this);
	}
	

}
